<template>
  <!--  @ok="handleSubmit"-->
  <BasicModal v-bind="$attrs" @register="register" showFooter :title="getTitle" width="75%" :showCancelBtn="false"
    :showOkBtn="false">
    <!--    <BasicForm @register="registerForm"> </BasicForm>-->
    <!--    :label-col="labelCol"-->
    <!--    :wrapper-col="wrapperCol"-->
    <Form :model="formData" label-align="right" ref="formRef">
      <div v-for="(item, index) in formSchemaList">
        <Divider v-if="item.component === 'divider'">{{ item.label }}</Divider>

        <FormItem v-bind="item" v-if="item.component" :name="item.field"
          v-show="(item.show != undefined && item.show) || item.show == undefined">
          <Input v-if="item.component === 'Input'" :placeholder="'请输入' + item.label"
            v-model:value="formData[item.field]"></Input>
          <InputNumber v-if="item.component === 'InputNumber'"
            :placeholder="item.placeholder ? item.placeholder : '请输入' + item.label"
            v-model:value="formData[item.field]"></InputNumber>

          <div v-if="item.items" style="display: flex">
            <!--            -->
            <!--              :class="{ 'ant-col': true,-->
            <!--               'ant-col-14': true,-->
            <!--              'item-row': true }"  m_w_100-->
            <FormItem :labelCol="{ span: 6 }" v-for="(item2, index2) in item.items" v-bind="item2"
              v-show="(item2.show != undefined && item2.show) || item2.show == undefined" :name="item2.field" :class="{
                'ant-col': true,
                'ant-col-10': item.items.length == 2,
                'ant-col-8': item.items.length === 3,
                'm_w_100': item.items.length == 1,
                'item-row': true
              }">
              <Switch v-if="item2.component === 'Switch'"
                :placeholder="item2.placeholder ? item2.placeholder : '请输入' + item2.label"
                v-model:checked="formData[item2.field]" @change="switchChangeFn"></Switch>
              <Input v-if="item2.component === 'Input'"
                :placeholder="item2.placeholder ? item2.placeholder : '请输入' + item2.label"
                v-model:value="formData[item2.field]"></Input>
              <div v-if="item2.component === 'div'" style="padding-left: 5px;">{{ formData[item2.field] }}</div>
              <InputNumber v-if="item2.component === 'InputNumber'" :placeholder="'请输入' + item2.label"
                :style="item2.field == 'baseNumber' && item2.componentProps.style" v-model:value="formData[item2.field]"
                :name="item2.field">
              </InputNumber>

              <Select v-if="item2.component === 'Select'" :placeholder="'请选择' + item2.label"
                v-model:value="formData[item2.field]" v-bind="item2.componentProps" @change="(v, o) => {
                  return returnTypeChange(v, o, item2.field);
                }
                  "></Select>

              <ApiSelect v-if="item2.component === 'ApiSelect'" :placeholder="'请选择' + item2.label"
                v-model:value="formData[item2.field]" @change="ApiSelectChangeFn" v-bind="item2.componentProps">
              </ApiSelect>

              <BasicUpload v-if="item2.component === 'Upload'" :placeholder="'请选择' + item2.label"
                v-model:value="formData[item2.field]" v-bind="item2.componentProps"></BasicUpload>
              <!--    规格-->
              <productSpecForm v-if="item2.component === 'productSpecForm'" v-model:value="formData[item2.field]"
                :data="formData" :isAdd="isAdd" @success="productSpecListuccessFn" :ref="setRefs(0)" @close="closeModal"
                v-bind="item2.componentProps"></productSpecForm>

            </FormItem>
          </div>
        </FormItem>
      </div>
    </Form>
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicForm, useForm } from '@/components/Form';
import { formSchema } from './role.data';
import { BasicModal, useModalInner } from '@/components/Modal';
import { ApiSelect, ApiTreeSelect } from '@/components/Form';

import { BasicTree, TreeItem } from '@/components/Tree';
import { saveProductApi, productDetailApi, getNoApi, saveSkuApi } from '@/api/sys/wmProduct';
import {
  Form,
  FormItem,
  Input,
  InputNumber,
  DatePicker,
  Select,
  Switch,
  Divider
} from 'ant-design-vue';
import { BasicUpload, ImageUpload } from '@/components/Upload';
import productSpecForm from "../components/productSpecForm/index.vue"
import { useMessage } from '@/hooks/web/useMessage';
import { useRefs } from '@vben/hooks';
import util from "@/utils/util";

const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);
const isAdd = ref(false);

const treeData = ref<TreeItem[]>([]);
const { refs, setRefs } = useRefs();

const { createMessage } = useMessage();

const formSchemaList = ref(formSchema)
const formData = ref({});
const labelCol = ref({ span: 10 });
const wrapperCol = ref({ span: 13 });
const formRef = ref();

const id = ref('');
const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 90,
  baseColProps: { span: 24 },
  schemas: formSchema,
  showActionButtonGroup: false,
});

const [register, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //打开弹层后的回调
  setModalProps({ confirmLoading: false });
  // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
  // if (unref(treeData).length === 0) {
  //   treeData.value = (await getMenuList()) as any as TreeItem[];
  // }
  isUpdate.value = data?.isUpdate;
  isAdd.value = !data?.isUpdate
  //console.log("--isAdd",isAdd.value)
  id.value = '';
  if (unref(isUpdate)) {
    // console.log("---data.record:",data.record)
    id.value = data.record.id;
    productDetailApi({
      prodId: id.value,
    }).then((res) => {
      //console.log(res)
      if (res.code == 200) {
        getBooksFn(res.data);
      }
    });
    // setFieldsValue({
    //   ...data.record,
    // });
  } else {
    getNoApi({ type: "product" }).then((res) => {
      //console.log(res)
      if (res.code == 200) {
        formData.value = {
          prodNumber: res.data,
          isPostage: 1,
          // isPostageValue: true,
        };
      }
    });

  }
});

const getTitle = computed(() => (!unref(isUpdate) ? '新增商品信息' : '编辑商品信息'));


async function handleSubmit() {
  try {

    // let productSpecFormRef = refs.value[0];

    // productSpecFormRef.submitFn();
    formRef.value
      .validate()
      .then(() => {


        setModalProps({ confirmLoading: true });
        const values = unref(formData.value);
        let skuObj = util.copy(values.skuObj);
        delete values.skuObj;
        if (values.isPostageValue) {
          //如果是包邮的话要清空邮费
          values.presellPrice = null;
        }
        // TODO custom api
        values.id = id.value;


        // return;
        //保存

        if (values.picArr) {
          values.pic = values.picArr.join(',');
        }
        if (values.picsArr) {
          values.pics = values.picsArr.join(',');
        }
        if (values.detailsArr) {
          values.details = values.detailsArr.join(',');
        }
        saveProductApi(values)
          .then((res) => {
            // console.log("---res::",res)
            // saveSkuApi({
            //   productId: res.data,
            //   productSkuList: skuObj.productSkuList,
            //   productSpecList: skuObj.productSpecList
            // })
            //   .then((res) => {
            //
            //
            //   })
            closeModal();
            emit('success');
            createMessage.success(res.message);
          })
          .catch((res) => {
            createMessage.error(res.message);

          })
          .finally(() => {

          });
      }).catch((error) => {
        // console.log('error', error);
        if (util.isNotEmpty(error.errorFields)) {
          let arr = [];
          error.errorFields.forEach(r => {
            //
            arr.push(r.errors[0] + "\n")

          });
          createMessage.error("您有以下这些信息未补充完整:" + arr.join(";"));

        }
      });


  } finally {
    setModalProps({ confirmLoading: false });
  }
}

function getBooksFn(data) {
  let item = data.product;
  if (item.pic) {
    item.picArr = item.pic.split(',');
  } else {
    item.picArr = [];
  }
  if (item.pics) {
    item.picsArr = item.pics.split(',');
  } else {
    item.picsArr = [];
  }
  if (item.details) {
    item.detailsArr = item.details.split(',');
  } else {
    item.detailsArr = [];
  }


  //console.log("---item:",item)
  // setFieldsValue(item);
  formData.value = item;
  if (util.isNotEmpty(data.productSkuList)) {
    data.productSkuList.forEach(r => {
      if (util.isNotEmpty(r.skuPic)) {
        r.skuPicValue = r.skuPic.split(",")
      }
      if (util.isNotEmpty(r.wmSkuSpecList)) {
        r.wmSkuSpecList.forEach(x => {
          r[x.specGroupName] = x.specName;
        })
      }
    })
  }
  if (util.isNotEmpty(data.productSpecList)) {
    data.productSpecList.forEach(r => {
      if (util.isNotEmpty(r.img)) {
        r.imgValue = r.img.split(",")
      }
    })
  }
  formData.value.skuObj = {
    productSkuList: data.productSkuList,
    productSpecList: data.productSpecList
  }


}


function switchChangeFn(v, o, field) {
  // console.log(v, o, field)
}

function returnTypeChange(v, o, field) {

}

function productSpecListuccessFn(data) {
  // console.log("--接收",data);
  formData.value.skuObj = data;
  // formData.value.productSpecList = data.productSpecList;
  // formData.value.productSkuList = data.productSkuList;
  formData.value.productSkuList = data.productSkuList;
  formData.value.productSpecList = data.productSpecList;
  handleSubmit()
}


function ApiSelectChangeFn(e, row) {

  formData.value.supplierName = row.value;
  formData.value.supplierId = row.supplierId;
  formRef.value.clearValidate();
}


</script>

<style lang="less">
.m_w_100 {
  width: 90%;

  .ant-col-6 {
    flex: 0 0 10%;
    max-width: 10%;
  }
}

.ant-form {
  .ant-form-item {
    margin-bottom: 10px;
  }
}
</style>
